package com.rsscollector.controller.user.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.log4j.Logger;
import org.compass.core.*;

import com.rsscollector.controller.user.form.SearchForm;
import com.rsscollector.model.vo.RssContent;
import com.rsscollector.model.RssSourceFacade;
import com.rsscollector.util.PersistenceUtil;

import java.util.List;
import java.util.ArrayList;

public class SearchAction extends Action {
    private static Logger logger = Logger.getLogger(SearchAction.class.getName());

    @Override
    public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
        SearchForm searchForm = (SearchForm) form;
        List result = new ArrayList();
        Compass compass = PersistenceUtil.getCompass();
        CompassSession session = compass.openSession();
        CompassTransaction tx = null;
        try {
            tx = session.beginTransaction();
            CompassQueryBuilder queryBuilder = session.queryBuilder();

            CompassHits hits = queryBuilder.queryString(searchForm.getTerm()).toQuery().hits();
            logger.debug("Search engine, found " + hits.getLength());
            if (hits.getLength() > 0) {
                RssContent item;
                RssContent hit;
                for (int i =0; i < hits.getLength(); i++) {
                    hit = (RssContent) hits.data(i);
                    item = RssSourceFacade.getNews(hit.getId());
                    result.add(item);
                }
            }
            tx.commit();
        } catch (CompassException ce) {
            if (tx != null) tx.rollback();
        } finally {
            session.close();
        }
        request.setAttribute("result", result);
        request.setAttribute("term", searchForm.getTerm());
        return mapping.findForward("success");
    }

    public static void print(CompassHits hits, int hitNumber) {
        RssContent value = (RssContent) hits.data(hitNumber);
        Resource resource = hits.resource(hitNumber);
        System.out.println("ALIAS [" + resource.getAlias() + "] ID [" +  value.getId() + "] SCORE ["
                + hits.score(hitNumber) + "]");
        System.out.println(":::: " + value.getTitle());
        System.out.println("");
    }

}
